package com.example.permission;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** PermissionPlugin */
public class PermissionPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  private Context context;

  private BluetoothAdapterStateReceiver bluetoothAdapterStateReceiver;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {

    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "permission");
    channel.setMethodCallHandler(this);

    context = flutterPluginBinding.getApplicationContext();

    IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    bluetoothAdapterStateReceiver = new BluetoothAdapterStateReceiver();
    context.registerReceiver(bluetoothAdapterStateReceiver, intentFilter);


    final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    boolean isEnabled = bluetoothManager.getAdapter().isEnabled();
    channel.invokeMethod("onAdapterStateChanged", isEnabled);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    if(context != null && bluetoothAdapterStateReceiver != null){
      context.unregisterReceiver(bluetoothAdapterStateReceiver);
    }

    context = null;

    channel.setMethodCallHandler(null);
    channel = null;
  }

  class BluetoothAdapterStateReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
      final String action = intent.getAction();

      // no change?
      if (!BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        return;
      }

      final int adapterState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

      channel.invokeMethod("onAdapterStateChanged", adapterState == BluetoothAdapter.STATE_ON);
    }
  }
}
